package com.eqdd.yiqidian.ui.gongneng.renshi.meeting

import android.app.Activity
import android.content.Intent
import android.support.v7.widget.RecyclerView
import android.view.View
import com.bigkoo.pickerview.TimePickerView
import com.eqdd.yiqidian.R
import com.eqdd.yiqidian.adapter.slimadapter.SlimInjector
import com.eqdd.yiqidian.base.Config
import com.eqdd.yiqidian.bean.DepartmentStaffTreeBean
import com.eqdd.yiqidian.bean.rebuild.RenwuSearchBean
import com.eqdd.yiqidian.bean.rebuild.slimedit.SlimEditEnterBean
import com.eqdd.yiqidian.bean.rebuild.slimedit.SlimTimeSelectBean
import com.eqdd.yiqidian.http.DialogCallBack
import com.eqdd.yiqidian.http.HttpConfig
import com.eqdd.yiqidian.http.HttpResult
import com.eqdd.yiqidian.ui.base.SlimBaseMultiEditActivity
import com.eqdd.yiqidian.ui.mine.renwu.RenwuListSearchActivity
import com.eqdd.yiqidian.ui.tongxunlu.stafftree.StaffTreeMultiActivity
import com.eqdd.yiqidian.ui.tongxunlu.stafftree.StaffTreeSingleActivity
import com.eqdd.yiqidian.utils.ToastUtil
import com.jhj.datalibrary.tree.multi.BaseMultiTreeActivity
import com.lzy.okgo.OkGo
import com.lzy.okgo.model.Response
import kotlinx.android.synthetic.main.activity_recyclerview.*
import org.jetbrains.anko.startActivityForResult
import org.jetbrains.anko.toast
import java.text.SimpleDateFormat
import java.util.*

/**
 * Created by jhj on 18-6-9.
 */
class MeetingRecordAddActivity : SlimBaseMultiEditActivity() {

    private var upDate: Date? = null
    private var downDate: Date? = null
    private var acceptDate: Date? = null
    private var isUpper: Boolean = false
    private var assistList: List<DepartmentStaffTreeBean>? = null
    private var notifyList: List<DepartmentStaffTreeBean>? = null


    override fun initBinding() {
        clearData()
        setContentView(R.layout.activity_recyclerview)
        val meetingId = intent.getIntExtra(Config.ID, -1)
        if (meetingId == -1) {
            toast("没有查询到该条会议")
            finish()
            return
        }
        initTopTitleBar(View.VISIBLE, "会议记录")
        initTopRightText("新增") { v ->
            if (!checkParams()) {
                toast(msg)
                return@initTopRightText
            }

            val bean = slimAdapterEx.data
            OkGo.post<HttpResult<*>>(HttpConfig.BASE_URL + HttpConfig.MEETING_RECORD_ADD)
                    .params("userGuid", user.guid)
                    .params("companyId", user.companyId)
                    .params("departId", user.departId)
                    .params("meetingNoticeId", meetingId)
                    .params("TaskName", bean[0].content)
                    .params("ParentTaskId", (bean[1].tag as? Int)?.toString())
                    .params("recipient", bean[2].tag as? String)
                    .params("assist", bean[3].tag as? String)
                    .params("notify", bean[4].tag as? String)
                    .params("startTime", bean[5].content)
                    .params("endTime", bean[6].content)
                    .params("checkStandard", bean[7].content)
                    .params("checker", bean[8].tag as? String)
                    .params("checkTime", bean[9].content)
                    .params("duty", "")
                    .params("taskDesc", bean[10].content)
                    .execute(object : DialogCallBack<HttpResult<*>>(this) {
                        override fun onSuccess(response: Response<HttpResult<*>>) {
                            val httpResult = response.body()
                            ToastUtil.showShort(httpResult.msg)
                            if (httpResult.status == 200) {
                                clearData()
                                setResult(Activity.RESULT_OK)
                                finish()
                            }
                        }
                    })
        }

    }

    override fun initRecyclerView(): RecyclerView {
        return recyclerView
    }

    override fun itemClick(p: Int) {
        when (slimAdapterEx.data[p].position) {
            1 -> {
                startActivityForResult<RenwuListSearchActivity>(Config.RENWU_LIST_SEARCH)
            }
            2 -> startActivityForResult<StaffTreeSingleActivity>(1000, Config.TITLE to "责任人",
                    Config.ID to 0, Config.TYPE to StaffTreeSingleActivity.TYPE_SINGLE_SELECT)
            3 -> startActivityForResult<StaffTreeMultiActivity>(1001, Config.TITLE to "协助人",
                    Config.ID to 0, Config.TYPE to StaffTreeMultiActivity.TYPE_CANYUREN, BaseMultiTreeActivity.SELECTED_DATA to assistList)
            4 -> startActivityForResult<StaffTreeMultiActivity>(1002, Config.TITLE to "知会人",
                    Config.ID to 0, Config.TYPE to StaffTreeMultiActivity.TYPE_CANYUREN, BaseMultiTreeActivity.SELECTED_DATA to notifyList)
            5 -> {
                isUpper = true
                openTimePicker()
            }
            6 -> {
                isUpper = false
                openTimePicker()
            }
            8 -> startActivityForResult<StaffTreeSingleActivity>(1003, Config.TITLE to "验收人",
                    Config.ID to 0, Config.TYPE to StaffTreeSingleActivity.TYPE_SINGLE_SELECT)
            9 -> {
                val sf = SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.CHINA)
                val now = Calendar.getInstance()
                if (acceptDate != null) {
                    now.time = acceptDate
                }
                TimePickerView
                        .Builder(this, TimePickerView.OnTimeSelectListener { date, v ->
                            acceptDate = date
                            slimAdapterEx.getDataItem(9).content = sf.format(date)
                            slimAdapterEx.notifyItemChanged(9)
                        })
                        .setOutSideCancelable(true)
                        .setType(booleanArrayOf(true, true, true, true, true, false))
                        .setDate(now)
                        .build()
                        .show()
            }
        }
    }

    override fun setEditBeans() {
        datas.add(SlimEditEnterBean("记录名称", "", 0, "请输入").setNeed(true))
        datas.add(SlimEditEnterBean("父项目", "", 1, "请选择").setDeal(true).setNeed(true))
        datas.add(SlimEditEnterBean("责任人", "", 2, "请选择").setDeal(true).setNeed(true))
        datas.add(SlimEditEnterBean("协助人", "", 3, "请选择").setDeal(true).setNeed(true))
        datas.add(SlimEditEnterBean("知会人", "", 4, "请选择").setDeal(true).setNeed(true))
        datas.add(SlimTimeSelectBean("开始时间", "", 5, "请选择").setStartTime(true).setDeal(true).setNeed(true))
        datas.add(SlimTimeSelectBean("结束时间", "", 6, "选择择").setStartTime(false).setDeal(true).setNeed(true))
        datas.add(SlimEditEnterBean("验收标准", "", 7, "请输入").setNeed(true))
        datas.add(SlimEditEnterBean("验收人", "", 8, "请选择").setDeal(true).setNeed(true))
        datas.add(SlimEditEnterBean("验收时间", "", 9, "请选择").setDeal(true).setNeed(true))
        datas.add(SlimEditEnterBean("记录描述", "", 10, "请输入").setNeed(true))
        slimAdapterEx.register(R.layout.list_item_29, SlimInjector<SlimTimeSelectBean> { data, injector ->
            injector?.text(R.id.tv_left_content, data?.title)
                    ?.text(R.id.tv_right_content, data?.content)
                    ?.hint(R.id.tv_right_content, data?.hint)
        })
    }

    private fun openTimePicker() {
        val sf = SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.CHINA)
        val now = Calendar.getInstance()
        if (isUpper && upDate != null) {
            now.time = upDate
        } else if (downDate != null) {
            now.time = downDate
        } else {
            now.time = Date()
        }
        TimePickerView
                .Builder(this, TimePickerView.OnTimeSelectListener { date, v ->
                    if (isUpper) {
                        upDate = date
                        if (downDate != null && upDate?.after(downDate) == true) {
                            toast("开始时间小于结束事件，请重新选择")
                            return@OnTimeSelectListener
                        }
                        slimAdapterEx.getDataItem(5).content = sf.format(date)
                        slimAdapterEx.notifyItemChanged(5)
                    } else {
                        downDate = date
                        if (upDate != null && upDate?.after(downDate) == true) {
                            ToastUtil.showShort("开始时间小于结束事件，请重新选择")
                            return@OnTimeSelectListener
                        }
                        slimAdapterEx.getDataItem(6).content = sf.format(date)
                        slimAdapterEx.notifyItemChanged(6)
                    }

                })
                .setOutSideCancelable(true)
                .setType(booleanArrayOf(true, true, true, true, true, false))
                .setDate(now)
                .build()
                .show()
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (data == null)
            return
        if (resultCode == Activity.RESULT_OK) {
            when (requestCode) {
                1000 -> {
                    val people = data.getSerializableExtra("data") as DepartmentStaffTreeBean?
                    datas[2].content = people?.name
                    datas[2].tag = people?.id
                    slimAdapterEx.notifyItemChanged(2)
                }
                1001 -> {//协助人
                    assistList = data.getSerializableExtra(BaseMultiTreeActivity.SELECTED_DATA) as? List<DepartmentStaffTreeBean>
                    val id = StringBuilder()
                    val name = StringBuilder()
                    assistList?.forEach {
                        id.append(it.id).append(",")
                        name.append(it.name).append(",")
                    }
                    datas[3].content = name.substring(0, name.length - 1)
                    datas[3].tag = id.substring(0, id.length - 1)
                    slimAdapterEx.notifyItemChanged(3)
                }

                1002 -> {//协助人
                    notifyList = data.getSerializableExtra(BaseMultiTreeActivity.SELECTED_DATA) as? List<DepartmentStaffTreeBean>
                    val id = StringBuilder()
                    val name = StringBuilder()
                    notifyList?.forEach {
                        id.append(it.id).append(",")
                        name.append(it.name).append(",")
                    }
                    datas[4].content = name.substring(0, name.length - 1)
                    datas[4].tag = id.substring(0, id.length - 1)
                    slimAdapterEx.notifyItemChanged(4)
                }
                1003 -> {
                    val people = data.getSerializableExtra("data") as DepartmentStaffTreeBean?
                    datas[8].content = people?.name
                    datas[8].tag = people?.id
                    slimAdapterEx.notifyItemChanged(8)
                }
            }
        }
        if (resultCode == Config.SUCCESS && requestCode == Config.RENWU_LIST_SEARCH) {
            val renwuSearchBean = data.getSerializableExtra("bean") as RenwuSearchBean
            datas[1].content = renwuSearchBean.getTaskName()
            datas[1].tag = renwuSearchBean.id
            slimAdapterEx.notifyItemChanged(1)
        }
    }
}